<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequestFn"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 进度条 -->
      <el-progress v-if="showProgress" type="circle" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDpYJyZ1GG2a9awKUQ8ct08FGD4kLjx266',
  SecretKey: '2zthQ4iJgw8HNJ3ZsxoQp1CIG3cw1sVu'
})
export default {
  name: 'UploadImg',
  props: {
    // 接收父组件传过来的头像
    imgUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '', // 图片
      percent: 0, // 图片的上传进度
      showProgress: false // 是够显示上传进度
    }
  },
  watch: {
    // 回显 监听自定义属性imgUrl的变化
    imgUrl() {
      this.imageUrl = this.imgUrl
    }
  },
  methods: {
    // 往后台上传成功后的回调函数
    handleAvatarSuccess(res, file) {
      // 前端图片预览
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义图片上传过程
    httpRequestFn(data) {
      // console.log(data.file.name)
      // 前端图片预览
      this.imageUrl = URL.createObjectURL(data.file)
      if (data.file) {
        // 显示进度条
        this.showProgress = true
        // 上传到云端存储(腾讯云)
        // 自己封装的上传方法
        // 简单上传接口适用于小文件上传，大文件请使用分块上传接口
        cos.putObject(
          {
            Bucket: 'tony-kai-1309370182' /* 必须: 存储桶的名称 */,
            Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
            Key: data.file.name /* 必须: 请求的对象键 */,
            StorageClass: 'STANDARD', // 对象存储类型
            Body: data.file, // 上传文件对象
            onProgress: progressData => {
              // 上传进度条
              // console.log(JSON.stringify(progressData))
              // 控制进度条的进度
              this.percent = parseInt(progressData.percent * 100)
            }
          },
          (err, data) => {
            if (err === null && data.statusCode === 200) {
              // this.imageUrl = `https:${data.Location}`
              this.$emit('update:imgUrl', `http://${data.Location}`)
              setTimeout(() => {
                // 隐藏进度条
                this.showProgress = false
              }, 1000)
            }
            // console.log(err || data)
          }
        )
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 2px dashed #8815d4;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #29e953;
  width: 160px;
  height: 160px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
